const Onion = require('./Onion');

async function pre1(ctx, next) {
  console.log('pre1');
  if (ctx.path === '/test') {
    ctx.redirect('/rdTest');
    console.log(ctx.status);
  } else {
    ctx.body = {
      list: []
    };
    ctx.body.list.push('pre1');
  }
  await next();
}

async function pre2(ctx, next) {
  console.log('pre2');
  ctx.body.list?.push('pre2');
  await next();
}

async function mid1(ctx, next) {
  console.log('mid1');
  ctx.body.list?.push('mid1');
  // await next();
}

async function mid2(ctx, next) {
  console.log('mid2');
  ctx.body.list?.push('mid2');
  await next();
}

async function post1(ctx, next) {
  console.log('post1');
  ctx.body.list?.push('post1');
  await next();
}

async function post2(ctx, next) {
  console.log('post2');
  ctx.body.list?.push('post2');
  await next();
}

function buildAuth(prefix, middleware, postfix) {
  return async (ctx, next) => {
    let preOnion = new Onion();
    let midOnion = new Onion();
    let postOnion = new Onion();
    preOnion.add(prefix);
    midOnion.add(middleware);
    postOnion.add(postfix);
    await preOnion.go(ctx);
    await midOnion.go(ctx);
    await postOnion.go(ctx);
    await next();
  }
}

let auth = buildAuth([pre1, pre2], [mid1, mid2], [post1, post2]);

module.exports = auth;